//
// Created by AssAs on 2024/9/23.
//

#include "app.h"

#include <audio_mem.h>
#include <audio_recorder.h>
#include <audio_thread.h>
#include <audio_tone_uri.h>
#include <audio_wrapper.h>
#include <blufi_app.h>
#include <board.h>
#include <button_control.h>
#include <esp_action_def.h>
#include <esp_audio.h>
#include <esp_delegate.h>
#include <esp_dispatcher.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <esp_peripherals.h>
#include <mqtt.h>
#include <periph_spiffs.h>
#include <sysGetConfig.h>
#include <freertos/event_groups.h>
#include <circuit_board.h>

/*----------------------blufi_app-------------------------*/
extern TaskHandle_t blufiAPPTaskHandle;
extern bool wifi_connected;
extern bool gl_sta_connected;
extern bool gl_sta_got_ip;
extern bool blufi_task_del_state;
/*--------------------------------------------------------*/

/*---------------------------parameters------------------------------*/
static const char *TAG = "APP";
static EventGroupHandle_t       chat_evt            = NULL;
static esp_audio_handle_t       player              = NULL;
static audio_rec_handle_t       recorder            = NULL;

uint32_t last_action_time = 0;
/*------------------------------------------------------------------*/

/*---------------------------audio_wrapper------------------------------*/
extern  bool voice_reading;
extern QueueHandle_t          rec_q ;
/*------------------------------------------------------------------*/

/*---------------------------button------------------------------*/
extern bool button_recorder;
/*------------------------------------------------------------------*/

/*---------------------------main parameters------------------------------*/
extern int msgId;          // 消息ID
/*------------------------------------------------------------------*/


static void retry_login_timer_cb(xTimerHandle tmr)
{
    ESP_LOGE(TAG, "Func:%s", __func__);
    // audio_service_connect(duer_serv_handle);
    xTimerStop(tmr, 0);
}

esp_err_t app_init_hal()
{

    ESP_ERROR_CHECK(esp_netif_init());

    // Initialize peripherals management
    esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
    esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);
    // 初始化SPIFFS外围设备
    periph_spiffs_cfg_t spiffs_cfg = {
        .root = "/spiffs", // SPIFFS根目录
        .partition_label = "storage", // 分区标签
        .max_files = 5, // 最大文件数
        .format_if_mount_failed = true // 如果挂载失败则格式化
};
    esp_periph_handle_t spiffs_handle = periph_spiffs_init(&spiffs_cfg); // 初始化SPIFFS外围设备
    // 启动SPIFFS和按钮外围设备
    esp_periph_start(set, spiffs_handle); // 启动SPIFFS外围设备

    // 等待SPIFFS挂载
    while (!periph_spiffs_is_mounted(spiffs_handle)) { // 如果SPIFFS未挂载
        vTaskDelay(100 / portTICK_PERIOD_MS);
    }

    audio_board_init();

    return ESP_OK;
}

static esp_err_t rec_engine_cb(audio_rec_evt_t *event, void *user_data)
{
    if (AUDIO_REC_WAKEUP_START == event->type) {
        recorder_sr_wakeup_result_t *wakeup_result = event->event_data;
        msgId++;
        chat_audio_stop_NOW();
        ESP_LOGI(TAG, "rec_engine_cb - REC_EVENT_WAKEUP_START");
        ESP_LOGI(TAG, "wakeup: vol %f, mod idx %d, word idx %d", wakeup_result->data_volume, wakeup_result->wakenet_model_index, wakeup_result->wake_word_index);
        if(!button_recorder) {
            play_tone(RESPONSE);
            if (voice_reading) {
                int msg = REC_CANCEL;
                if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                    ESP_LOGE(TAG, "rec cancel send failed");
                }
            }
        }

    } else if (AUDIO_REC_VAD_START == event->type) {
        ESP_LOGI(TAG, "rec_engine_cb - AUDIO_REC_VAD_START");
        if(!button_recorder) {
            if (!voice_reading) {
                int msg = REC_START;
                if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                    ESP_LOGE(TAG, "rec start send failed");
                }
            }
        }
    } else if (AUDIO_REC_VAD_END == event->type) {
        ESP_LOGI(TAG, "rec_engine_cb - AUDIO_REC_VAD_STOP");
        //非按键模式进行VAD检测，按键模式下通过stop——recorder控制
        if(!button_recorder) {
            if (voice_reading) {
                int msg = REC_STOP;
                if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                    ESP_LOGE(TAG, "rec stop send failed");
                }
            }
        }
    } else if (AUDIO_REC_WAKEUP_END == event->type) {
        ESP_LOGI(TAG, "rec_engine_cb - AUDIO_REC_WAKEUP_END");
    } else {

    }

    return ESP_OK;
}

void app_chat(void){

    app_init_hal();

    audio_wrapper_init();
    chat_evt = xEventGroupCreate();

    player = chat_audio_setup_player();

    set_language(LANGUAGE_CHINESE);
    play_tone(TURN_ON);

    //网络链接
    xTaskCreate(blufi_app_main, "blufi_app_main", 1024 * 4, NULL, 8, &blufiAPPTaskHandle);

    button_control_init();

    while (!gl_sta_got_ip || !blufi_task_del_state)
    {
        vTaskDelay(100);
    }

    get_sysConfig_init();
    get_sysConfig_On_Starting();

    recorder = chat_audio_start_recorder(rec_engine_cb);

    mqtt_app_start();

}